package com.coderg.gmall.user.filter;

import com.coderg.gmall.user.util.GmallThreadLocalUtils;
import com.coderg.gmall.user.util.TokenUtil;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @Description
 * @Author CoderG
 * @Date 2025/6/10 18:22
 **/
@WebFilter(filterName = "orderFilter", urlPatterns = "/*")
@Order(1)
public class OrderFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //获取请求头的token 解析出用户名 放入ThreadLocal
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("Authorization").replace("Bearer ", "");

        Map<String, String> decodeToken = TokenUtil.dcodeToken(token);

        String username = decodeToken.get("username");
        GmallThreadLocalUtils.setUserName(username);

        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }


}
